package com.gsta.ifishery.netty.handler;

import com.gsta.ifishery.common.util.NettyServerUtils;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 异常监测 . <br>
 * 
 * @author hkb
 */
public class AbnormalMonitoringHandler extends SimpleChannelInboundHandler<String> {

    /**
     * 监测channel
     */
    private static ChannelGroup abnormalChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        abnormalChannels.add(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel incoming = ctx.channel();
        String clientIp = NettyServerUtils.getClientIp(ctx);
        for (Channel channel : abnormalChannels) {
            if (channel != incoming) {
                String findClientIp = channel.remoteAddress().toString().replace("/", "");
                if (findClientIp.contains(clientIp)) {
                    // TODO 返回响应码
                    channel.close();
                }
            }
        }
        ctx.fireChannelRead(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 当出现异常就关闭连接
        ctx.close();
    }

}
